// createWebHashHistory 是hash模式就是访问链接带有#
// createWebHistory  是history模式
import {
    createRouter,
    createWebHashHistory,
    createWebHistory,
} from "vue-router";
import system from "./system";
import user from "./user";
import enterprise from "./enterprise";
import outlets from "./outlets";
import file from "./file";
import store from "./store";
import staff from "./staff";
import order from "./order";
import shop from "./shop";
import option from "./option";
import message from "./message";
import marketing from "./marketing";
import { useUserStore } from "@stores/user";
import { ElMessage, ElNotification, ElButton } from "element-plus";
import { h } from "vue";
import { userLogout } from "@/assets/common/utils";

const routes = [
    {
        path: "/",
        name: "Login",
        meta: {
            title: "登录",
        },
        component: () => import("../views/Login.vue"),
    },
    {
        path: "/Home",
        name: "Home",
        meta: {
            title: "控制台",
        },
        component: () => import("../views/Home.vue"),
    },

    // 系统管理
    ...system,
    // 系统文件下载
    ...file,
    // 网点管理
    ...outlets,
    // 员工管理
    ...staff,
    // 用户管理
    ...user,
    // 商家管理
    ...store,
    // 企业配置
    ...enterprise,
    // 订单管理
    ...order,
    // 店铺管理
    ...shop,
    // 其他配置
    ...option,
    // 消息管理
    ...message,
    // 营销
    ...marketing,
    {
        path: "/ChangePass",
        name: "ChangePass",
        meta: {
            title: "修改密码",
        },
        component: () => import("../views/ChangePass.vue"),
    },
    {
        path: "/Page403",
        name: "Page403",
        meta: {
            title: "页面403",
        },
        component: () => import("../views/Page403.vue"),
    },
    {
        path: "/:pathMatch(.*)*", // 代替vue2的通配符path: "*",
        name: "Page404",
        meta: {
            title: "页面404",
        },
        component: () => import("../views/Page404.vue"),
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

// 路由拦截
router.beforeEach((to, from) => {
    if (to.meta.title) {
        document.title = to.meta.title + " - 花数通物流企业";
    } else {
        document.title = "花数通物流企业";
    }

    if (!["Login", "Page403", "Page404"].includes(to.name)) {
        const token = localStorage.getItem("token");
        if (!token) {
            ElMessage.error("请先登录");
            userLogout();
            return { name: "Login", replace: true };
        }

        if (/List$/.test(to.name)) {
            const user = useUserStore();
            user.addKeepAlive(to.name);
        }
    }
});

// 标记是否显示过版本更新弹窗，防止重复弹窗
let showUpdate = false;
router.onError((callback) => {
    console.log("routerError", callback);
    if (!showUpdate) {
        // 读取 public 下的 version.json 文件，判断版本是否更新
        fetch(`version.json?time=${Date.now()}`)
            .then((response) => response.json())
            .then((data) => {
                const version = data.version;
                if (
                    version &&
                    String(version) !== localStorage.getItem("__APP_VERSION__")
                ) {
                    showUpdate = true;
                    ElNotification({
                        title: "版本更新",
                        message: h("div", {}, [
                            h(
                                "p",
                                {},
                                "检测到版本更新，需更新才能正常使用，请保存好要提交的数据！"
                            ),
                            h(
                                ElButton,
                                {
                                    link: true,
                                    type: "primary",
                                    onClick: () => {
                                        window.location.replace("/");
                                    },
                                },
                                "立即更新"
                            ),
                        ]),
                        duration: 0,
                        showClose: false,
                    });
                }
            })
            .catch((error) => {
                console.log("error", error);
            });
    }
});

export default router;
